package com.huicoo.forestmanager.ui.patrol.MapFragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.huicoo.forestmanager.R;
import com.huicoo.forestmanager.base.BaseFragment;
import com.huicoo.forestmanager.network.bean.patrol.PatrolToDoList;
import com.huicoo.forestmanager.network.bean.patrol.PatrollingTasksinif;
import com.huicoo.forestmanager.others.TaskFinishEvent;
import com.huicoo.forestmanager.ui.patrol.MapFragment.contract.MapFragmentContract;
import com.huicoo.forestmanager.ui.patrol.MapFragment.presenter.MapFragmentPresenter;
import com.huicoo.forestmanager.ui.patrol.forestCampTask.ForestCampTaskActivity;
import com.huicoo.forestmanager.util.JsonUtils;
import com.huicoo.forestmanager.util.LogUtils;
import com.huicoo.forestmanager.util.MulchUtil;
import com.huicoo.forestmanager.widget.LoadingDialog;
import com.tianditu.android.maps.GeoPoint;
import com.tianditu.android.maps.MapController;
import com.tianditu.android.maps.MapView;
import com.tianditu.android.maps.MyLocationOverlay;
import com.tianditu.android.maps.overlay.MarkerOverlay;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.tianditu.android.maps.MapView.LOGO_RIGHT_BOTTOM;
import static com.tianditu.android.maps.MapView.TMapType.MAP_TYPE_IMG;
import static com.tianditu.android.maps.MapView.TMapType.MAP_TYPE_VEC;

/**
 * --------- 日期 ------- 维护人 ------------ 变更内容 --------
 * 2019/4/5		    Administrator
 * <p>
 * 地图片段
 */
public class MapFragment extends BaseFragment implements MapFragmentContract.View, MarkerOverlay.OnMarkerClickListener {


    @BindView(R.id.map_view)
    MapView map_view;

    @BindView(R.id.bottom_rl)
    RelativeLayout bottom_rl;

    @BindView(R.id.positioning)
    ImageView positioning;

    @BindView(R.id.subtract)
    ImageView subtract;

    @BindView(R.id.add)
    ImageView add;


    @BindView(R.id.title)
    TextView title;

    @BindView(R.id.content)
    TextView content;

    @BindView(R.id.time)
    TextView time;

    @BindView(R.id.iv_status)
    ImageView iv_status;

    @BindView(R.id.map_type_iv)
    ImageView map_type_iv;

    @BindView(R.id.map_type_tv)
    TextView map_type_tv;

    @BindView(R.id.map_type_ll)
    LinearLayout map_type_ll;

    @BindView(R.id.turn_back)
    ImageView turn_back;

    LoadingDialog loadingDialog;


    private MapController mMapController;
    private MyLocationOverlay myLocationOverlay;
    private List<PatrollingTasksinif> mPatrollingTasks;
    private PatrollingTasksinif mPatrollingTasksinif;
    Handler mHandler = new Handler();
    private ImageView mImageView;

    public static MapFragment getInstance() {
        return new MapFragment();
    }


    @Override
    protected int getLayoutId() {
        return R.layout.fragment_map;
    }

    @Override
    protected void initView() {
        //初始化地图设置
        initMapView();

        //初始化数据
        initData();
    }


    //初始化数据
    private void initData() {
        loadingDialog = new LoadingDialog(getActivity());
        // 初始化P层
        presenter = new MapFragmentPresenter(this);

        EventBus.getDefault().register(this);

        requestData();
    }

    private void requestData() {
        if (loadingDialog != null) {
            loadingDialog.show();
        }
        // 获取待巡林班列表
        ((MapFragmentPresenter) presenter).patrolToDoList();
    }


    //初始化地图设置
    private void initMapView() {
        //设置启用内置的缩放控件
        map_view.setBuiltInZoomControls(false);

        //得到mMapView的控制权,可以用它控制和驱动平移和缩放
        mMapController = map_view.getController();

        //创建MyLocationOverlay
        myLocationOverlay = new MyLocationOverlay(getContext(), map_view);

        //启用指南针位置更新
        myLocationOverlay.enableCompass();

        //启用我的位置
        myLocationOverlay.enableMyLocation();

        map_view.addOverlay(myLocationOverlay);

        //定位到当前位置
        locateCurrentLocation();

        //设置地图zoom级别
        mMapController.setZoom(15);

        //设置Logo显示位置.
        map_view.setLogoPos(LOGO_RIGHT_BOTTOM);

        //矢量
        map_view.setMapType(MAP_TYPE_VEC);
        map_type_tv.setText("影像");


        mImageView = new ImageView(getActivity());
        mImageView.setImageResource(R.mipmap.map_marker_hot);
        mImageView.setVisibility(View.GONE);
        map_view.addView(mImageView);
    }

    //定位到当前位置
    private void locateCurrentLocation() {
        //获得当前位置
        GeoPoint myLocation = myLocationOverlay.getMyLocation();

        //设置地图中心点
        mMapController.setCenter(myLocation);

        //动画移动到当前位置
        mMapController.animateTo(myLocation);
    }


    //定位
    @OnClick(R.id.positioning)
    public void positioning() {
        //定位到当前位置
        locateCurrentLocation();
    }


    //回到
    @OnClick(R.id.turn_back)
    public void turnBack() {
        if (mPatrollingTasks != null && mPatrollingTasks.size() > 0) {
            //中心定位
            MulchUtil.centerPositioning(map_view, mPatrollingTasks);
        }
    }


    //减
    @OnClick(R.id.subtract)
    public void subtract() {
        // 缩小一级
        mMapController.zoomOut();

    }

    //加
    @OnClick(R.id.add)
    public void add() {
        // 放大一级
        mMapController.zoomIn();
    }

    @OnClick(R.id.map_type_ll)
    public void mapTypeLl() {

        //当前是影像
        if (map_view.getMapType() == MAP_TYPE_IMG) {
            map_type_iv.setImageResource(R.mipmap.icon_satellite);
            map_view.setMapType(MAP_TYPE_VEC);
            map_type_tv.setText("影像");
        } else if (map_view.getMapType() == MAP_TYPE_VEC) {
            map_type_iv.setImageResource(R.mipmap.icon_plane);
            //矢量
            map_view.setMapType(MAP_TYPE_IMG);
            map_type_tv.setText("平面");
        }


    }


    @OnClick(R.id.bottom_rl)
    public void bottom() {

        if (mPatrollingTasksinif == null) {
            return;
        }
        Bundle bundle = new Bundle();
        bundle.putString("detail", JsonUtils.toJson(mPatrollingTasksinif));
        Intent intent = new Intent(getActivity(), ForestCampTaskActivity.class);
        intent.putExtras(bundle);
        startActivity(intent);
    }


    @Override
    public void patrolListSuccess(PatrolToDoList data) {
        loadingDialog.dismiss();
        mPatrollingTasks = data.getData().patrollingTasks;

//        mPatrollingTasksinif = mPatrollingTasks.get(0);
//        //刷新地图条目
//        refreshMapEntries();

        //清空覆盖物
        map_view.removeAllOverlay();
        //添加林地图标
        MulchUtil.addWoodlandMulch(getActivity(), map_view, 0, mPatrollingTasks, this);

        //中心定位
        MulchUtil.centerPositioning(map_view, mPatrollingTasks);


//        //用给定的经纬度构造一个GeoPoint，单位是微度 (度 * 1E6)
//        GeoPoint point = new GeoPoint(
//                (int) (patrollingTasks.get(0).getForestArea().getCenter().getLatitude() * 1E6),
//                (int) (patrollingTasks.get(0).getForestArea().getCenter().getLongitude() * 1E6));
//        //设置地图中心点
//        mMapController.setCenter(point);
    }


    @Override
    public void patrolListFail(String msg) {
        loadingDialog.dismiss();
    }

    @Override
    public boolean onMarkerClick(MarkerOverlay marker) {

        int location = Integer.parseInt(marker.getTitle());

        if (mPatrollingTasks != null && mPatrollingTasks.size() > 0) {
            mPatrollingTasksinif = mPatrollingTasks.get(location);
            //刷新地图条目
            refreshMapEntries();
        }

        map_view.updateViewLayout(mImageView, new MapView.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT,
                new GeoPoint(
                        (int) (mPatrollingTasksinif.getForestArea().getCenter().getLatitude() * 1E6),
                        (int) (mPatrollingTasksinif.getForestArea().getCenter().getLongitude() * 1E6)),
                MapView.LayoutParams.BOTTOM_CENTER));
        mImageView.setVisibility(View.VISIBLE);


//        mHandler.postDelayed(new Runnable() {
//            public void run() {
//                map_view.removeAllOverlay();
//                map_view.postInvalidate();
//                //添加林地图标
//                MulchUtil.addWoodlandMulch(getActivity(), map_view, location, mPatrollingTasks, MapFragment.this);
//            }
//
//        }, 300);


        return true;
    }

    //刷新地图条目
    private void refreshMapEntries() {
        if (mPatrollingTasksinif == null) {
            return;
        }

        if (bottom_rl.getVisibility() != View.VISIBLE) {
            bottom_rl.setVisibility(View.VISIBLE);
        }

        title.setText(mPatrollingTasksinif.getForestArea().getSerialNumber());

        content.setText((mPatrollingTasksinif.getCounty() == null ? "" : mPatrollingTasksinif.getCounty().getName())
                + (mPatrollingTasksinif.getTown() == null ? "" : mPatrollingTasksinif.getTown().name)
                + (mPatrollingTasksinif.getVillage() == null ? "" : mPatrollingTasksinif.getVillage().name));

        time.setText(mPatrollingTasksinif.getStartTime());

        int status = mPatrollingTasksinif.getForestArea().getRecordStatus();
        if (status == 0) {
            iv_status.setImageResource(R.drawable.icon_waiting);
        } else if (status == 1) {
            iv_status.setImageResource(R.drawable.icon_doing);
        } else if (status == 100) {
            iv_status.setImageResource(R.drawable.icon_done);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void taskFinishEvent(TaskFinishEvent event) {
        LogUtils.v("gogogo get task finish event");
        requestData();
    }
}
